package java_option.audio_a012.audio;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import javafx.concurrent.Task;

/**
 * 音频播放
 * 
 * @author java_option
 * @date 2020-10-31
 */
public class AudioPlay {

	private Clip clip;
//
	private List<PlayItem> playList = new ArrayList<>();
	private int index = -1;

	class PlayItem {
		String wavFile;
		long microseconds;
	}

	public AudioPlay(String... audios) {
		for (String audio : audios) {
			if (new File(audio).exists() == false) {
				continue;
			}
			PlayItem item = new PlayItem();
			item.wavFile = audio;
			item.microseconds = 0;
			playList.add(item);
		}
	}

	public void addFile(String wavFile) {

//
		if (this.index != -1) {
			this.onStop();
		}
//
		PlayItem item = new PlayItem();
		item.wavFile = wavFile;
		item.microseconds = 0;
		playList.add(0, item);

//
//

		this.onStart(0, 0);

		new Thread(new Task<Void>() {
			@Override
			protected Void call() throws Exception {
				int oldIndex = index;
				while (true) {
					if (clip.getMicrosecondPosition() == clip.getMicrosecondLength()) {
						if (oldIndex != -1) {
							oldIndex++; //
							PlayItem pi = playList.get(oldIndex);
							onStart(oldIndex, pi.microseconds);
						}
						break;
					}
				}
				return null;
			}
		}).start();

	}

	/**
	 * @param microSeconds 微秒
	 */
	public void onStart(int index, long microSeconds) {
		if (index >= playList.size()) {
			System.out.println("参数非法 ");
			return;
		}
//
		if (this.index == index && this.clip != null) {
			this.clip.start();
			return;
		}
//
		this.index = index;
		PlayItem item = playList.get(index);
//
		if (this.clip != null) {
			this.clip.stop();
			this.clip.close();
			this.clip = null;
		}
		try {
			String file = item.wavFile;
			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(file).getAbsoluteFile());
			clip = AudioSystem.getClip();
			clip.open(audioInputStream);
		} catch (Exception ex) {
			System.out.println("Error with playing sound.");
			ex.printStackTrace();
		}
		clip.setMicrosecondPosition(microSeconds);
		clip.start();
	}

	public void onPause() {
		PlayItem item = playList.get(index);
		item.microseconds = clip.getMicrosecondPosition();
		clip.stop();
	}

	public void onResume() {
		clip.start();
	}

	public void onStop() {
		onPause();//
		clip.close();
		clip = null;
	}

}
